// 导入数据库操作模块
const db = require('../db/index')

// 展示云养中心
exports.showAdoptedDog = (req, res) => {

    const sql = `SELECT *
    FROM adopted_dog
    WHERE adopted_dog.id NOT IN (SELECT adopted.adopteddog_id
    FROM adopted
    WHERE isDeleted = 0)`

    db.query(sql, function (err, results) {
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "查询出错", message: err.message });
        }
        return res.send(results);

    })

}

// 通过领养宠物id获取图片路径
exports.showAdoptedDogImg = (req, res) => {
    const adopteddog_id = req.body.adopteddog_id;

    const sql = `SELECT *
    FROM adopted_dog_img
    WHERE adopteddog_id = ?`

    db.query(sql, [adopteddog_id], function (err, results) {
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "无法获取图片信息", message: err.message });
        }
        return res.send(results);
    })
}

// 通过ID查询云养狗狗信息
exports.queryAdoptedDogById = (req, res) => {
    const data = req.body;
    const adoptedId = data.adoptedId;
    console.log(req.body);
    console.log(adoptedId);

    const sql = `SELECT *
    FROM adopted_dog
    WHERE id = ? `

    db.query(sql, [adoptedId], function (err, results) {
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "查询出错", message: err.message })
        }

        return res.send(results)

    })
}

// 通过name查询云养狗狗信息
exports.queryAdoptedDogByName = (req, res) => {
    const data = req.body;
    const adoptedName = data.adoptedName;
    console.log(req.body);
    console.log(adoptedName);

    const sql = `SELECT *
                FROM adopted_dog
                WHERE adopted_dog.id NOT IN (SELECT adopted.adopteddog_id
                FROM adopted
                WHERE isDeleted = 0) 
                AND name=? `;

    db.query(sql, [adoptedName], function (err, results) {
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "查询出错", message: err.message })
        }
        return res.send(results)

    })
}

// 通过userID查询我的云养
exports.queryAdoptedByUserId = (req, res) => {
    const data = req.body;
    const userId = data.userId;
    console.log(req.body);
    console.log(userId);

    const sql = `select adopted_dog.id,name,story,img 
                from adopted_dog,adopted
                where adopted.adopteddog_id=adopted_dog.id
                and isDeleted=0
                and adopted.user_id=? `

    db.query(sql, [userId], function (err, results) {
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "查询出错", message: err.message })
        }

        return res.send(results)

    })
}

// 通过userID查询我的云养记录
exports.queryMyAdoptedListByUserId = (req, res) => {
    const data = req.body;
    const userId = data.userId;
    console.log(req.body);
    console.log(userId);

    const sql = `select adopted_dog.id,name,img,sex,age,weight,isGrown,isExpelled,isSterilized,isVaccinated,story,pay_time,adopted_amount
    from adopted_dog,adopted,adopted_payment
    where adopted.adopteddog_id=adopted_dog.id
                    and adopted_payment.adopted_id = adopted.id
                    and isDeleted = 0
    and adopted.user_id= ? `

    db.query(sql, [userId], function (err, results) {
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "查询出错", message: err.message })
        }

        return res.send(results)

    })
}


// 绑定云养人与云养宠物
exports.bindAdoptedDogWithUser = (req, res) => {
    const data = req.body;
    const id = "adopted" + new Date().getTime();
    const user_id = data.user_id;
    const adopteddog_id = data.adopteddog_id;
    console.log(req.body);
    console.log(id);
    console.log(user_id);
    console.log(adopteddog_id);


    const sql1 = `select * from user where id = ?`;
    const sql2 = `SELECT *
                    FROM adopted_dog
                    WHERE adopted_dog.id NOT IN (SELECT adopted.adopteddog_id
                    FROM adopted
                    WHERE isDeleted = 0)
                    AND id = ?`;
    const sql3 = `select * from adopted where user_id=? and adopteddog_id=? and isDeleted=0`;
    const sqlStr = `insert into adopted(id,user_id,adopteddog_id) 
                    values (?,?,?) `;
    db.query(sql1, [user_id], function (err, results) {
        if (results.length == 0) {
            return res.send({ status: "用户不存在" });
        } else {
            db.query(sql2, [adopteddog_id], function (err, results) {
                if (results.length == 0) {
                    return res.send({ status: "宠物已经被领养走啦" });
                } else {
                    db.query(sql3, [user_id, adopteddog_id], function (err, results) {
                        if (results.length != 0) {
                            return res.send({ status: "您已经领养过该宠物" });
                        } else {
                            db.query(sqlStr, [id, user_id, adopteddog_id], function (err, results) {
                                if (err) {
                                    return res.send({ status: "云养失败", message: err.message })
                                }
                                return res.send({ status: "云养成功" });
                            });
                        }
                    });
                }
            });
        }
    });


}

// 发布云养宠物信息
exports.addAdoptedDogInfo = (req, res) => {
    const data = req.body;
    const id = "adopteddog" + new Date().getTime();
    const name = data.name;
    const img = JSON.parse(data.img);
    const sex = data.sex;
    const age = data.age;
    const weight = data.weight;
    const isGrown = data.isGrown;
    const isExpelled = data.isExpelled;
    const isSterilized = data.isSterilized;
    const isVaccinated = data.isVaccinated;
    const story = data.story;
    console.log(req.body);

    const sqlStr = `insert into adopted_dog(id,name,img,sex,age,weight,isGrown,isExpelled,isSterilized,isVaccinated,story) 
                    values (?,?,?,?,?,?,?,?,?,?,?)`;
    const sqlStr2 = `insert into adopted_dog_img(id,adopteddog_id,img) values (?,?,?)`;

    db.query(sqlStr, [id, name, img[0], sex, age, weight, isGrown, isExpelled, isSterilized, isVaccinated, story], function (err, results) {
        if (err) {
            return res.send({ status: "发布失败", message: err.message })
        } else {
            for (let i = 0; i < img.length; i++) {
                const id2 = "adopteddogimg" + new Date().getTime() + i;
                db.query(sqlStr2, [id2, id, img[i]], function (err, results) {
                    if (err) {
                        return res.send({ status: "发布失败", message: err.message })
                    }
                })
            }
        }
    })
    return res.send({ status: "发布成功" });
}


// 查看所有云养信息
exports.showAllAdoptedInfo = (req, res) => {
    const sqlStr = `SELECT  adopted.id,start_time,isOvertime,user_id,adopteddog_id , user.name as user_name,user.img as user_img, 
    adopted_dog.name as dog_name,adopted_dog.img as dog_img
    from adopted
		inner join user
		on adopted.user_id = user.id
		inner join adopted_dog
		on adopted.adopteddog_id = adopted_dog.id
    where isDeleted=0`;
    db.query(sqlStr, function (err, results) {
        if (err) {
            return res.send({ status: "查询失败", message: err.message })
        }
        return res.send(results);
    })
}


// 解除云养关联
exports.deleteAdoptedInfo = (req, res) => {
    const data = req.body;
    const user_id = data.user_id;
    const adopteddog_id = data.adopteddog_id;
    console.log(req.body);

    const sqlStr = `update adopted set isDeleted=1 where user_id=? and adopteddog_id=?`;
    db.query(sqlStr, [user_id, adopteddog_id], function (err, results) {
        if (err) {
            return res.send({ status: "解除关联失败", message: err.message })
        }
        return res.send({ status: "解除关联成功" });
    })
}

// 添加云养支付记录
exports.addAdoptedPaymentInfo = (req, res) => {
    const data = req.body;
    const id = "adoptedpayment" + new Date().getTime();
    const user_id = data.user_id;
    const adopteddog_id = data.adopteddog_id;
    const adopted_amount = data.adopted_amount;
    console.log(req.body);

    const sql = `select id from adopted where user_id=? and adopteddog_id=? and isDeleted=0`;
    const sqlStr = `insert into adopted_payment(id,adopted_id,adopted_amount) 
                    values (?,?,?)`;
    db.query(sql, [user_id, adopteddog_id], function (err, results) {
        if (err) {
            return res.send({ status: "添加失败", message: err.message })
        } else if (results.length == 0) {
            return res.send({ status: "不存在该条领养信息" });
        } else if (results.length != 0) {
            db.query(sqlStr, [id, results[0].id, adopted_amount], function (err, results) {
                if (err) {
                    return res.send({ status: "添加失败", message: err.message })
                }
                return res.send({ status: "添加成功" });
            })
        }
    });

}


// 通过ID修改云养狗狗信息
exports.updateAdoptedDogById = (req, res) => {
    const data = req.body;
    const id = data.adoptedId;
    const name = data.name;
    const img = JSON.parse(data.img);
    const sex = data.sex;
    const age = data.age;
    const weight = data.weight;
    const isGrown = data.isGrown;
    const isExpelled = data.isExpelled;
    const isSterilized = data.isSterilized;
    const isVaccinated = data.isVaccinated;
    const story = data.story;

    const sql = `UPDATE adopted_dog 
                 SET name = ?,img = ?,sex = ?,age = ?,weight = ?,isGrown = ?,
                 isExpelled = ?,isSterilized = ?,isVaccinated = ?,story = ?
                 WHERE id=?; `

    const sqlStr2 = `insert into feeded_dog_img(id,feededdog_id,img) values (?,?,?)`;

    db.query(sql, [name, img[0], sex, age, weight, isGrown, isExpelled, isSterilized, isVaccinated, story, id], function (err, results) {
        if (err) {
            return res.send({ status: "修改出错", message: err.message })
        } else {
            for (let i = 0; i < img.length; i++) {
                const id2 = "adopteddogimg" + new Date().getTime() + i;
                db.query(sqlStr2, [id2, id, img[i]], function (err, results) {
                    if (err) {
                        return res.send({ status: "添加图片失败", message: err.message })
                    }
                })
            }
        }
    })

    return res.send({ status: "修改成功" });
}

// 通过id删除云养狗狗信息
exports.deleteAdoptedDogById = (req, res) => {
    const adoptedId = req.body.adoptedId;
    console.log(req.body);

    const sql = `delete from adopted_dog
                 where id = ?; `
    const sql2 = `delete from adopted_dog_img
              where adopteddog_id = ?`
    db.query(sql, [adoptedId], function (err, results) {
        console.log("########deleteAdoptedDogById#######")
        console.log(results);
        console.log("########deleteAdoptedDogById end#######")
        // 执行 SQL 语句失败
        if (err) {
            return res.send({ status: "删除出错", message: err.message })
        } else {
            db.query(sql2, [adoptedId], function (err, results) {
                if (err) {
                    return res.send({ status: "删除图片出错", message: err.message })
                }
            })
        }

        return res.send({ status: "删除成功", message: results })

    })
}

